package com.study.web.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * DefaultMessageDelegate.java
 * 
 * @author yaojinshan
 * @since 2018年5月15日上午9:32:35
 */
public class DefaultMessageDelegate implements MessageListener {
	public static Logger logger = LoggerFactory.getLogger(DefaultMessageDelegate.class);

	public void onMessage(Message message, byte[] pattern) {
		System.out.println("channel:" + new String(message.getChannel()) + ",message:" + new String(message.getBody()));
        System.out.println(convertBodyByteToObject(message.getBody()));
	}
	/**
	　* @description: 因为序列化构造器使用的问题 导致new String(message.getBody()出现乱码 所以需要转换body字节数据到object对象。
	　* @author yaojinshan
	　* @date 2019/5/23 10:33
	　*/
	public Object convertBodyByteToObject(byte[] body){
        if (body == null) {
            return null;
        }
        ObjectInputStream ois = null;
        try{
            ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(body)));
            return ois.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
